package controller

import (
	"github.com/cy77cc/hioshop/forms"
	"github.com/cy77cc/hioshop/models"
	"github.com/cy77cc/hioshop/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

type IndexHandler struct {
}

func (i *IndexHandler) GetAppInfo(ctx *gin.Context) {
	//fmt.Println(ctx.Get("id"))
	res := utils.NewResponse()
	id, exits := ctx.Get("id")
	if !exits {
		res.SetRes(1, "id不存在", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	userId := id.(uint)
	//id := 10
	appInfo := forms.AppInfo{}

	// 总共包含四个数据库
	ad := models.Ad{}

	list, err := ad.GetAds()
	appInfo.Banner = list

	if err != nil {
		res.SetRes(1, "error", err)
		ctx.JSON(http.StatusOK, res)
		return
	}

	notice := models.Notice{}
	noticeList, err := notice.GetNotices()
	if err != nil {
		res.SetRes(1, "error", err)
		ctx.JSON(http.StatusOK, res)
		return
	}
	appInfo.Notice = noticeList

	category := models.Category{}
	channelList, err := category.GetCategoriesByChannel()
	if err != nil {
		res.SetRes(1, "error", err)
		ctx.JSON(http.StatusOK, res)
		return
	}

	appInfo.Channel = channelList
	// 获取category列表
	categoryList, err := category.GetCategories()
	if err != nil {
		res.SetRes(1, "error", err)
		ctx.JSON(http.StatusOK, res)
		return
	}

	appInfo.CategoryList = make([]forms.Category, 0)
	for _, v := range categoryList {
		goods := models.Goods{}
		formCategory := forms.Category{}
		formCategory.Id = v.ID
		formCategory.Name = v.Name
		formCategory.Banner = v.ImgUrl
		formCategory.Height = v.PHeight
		goodsList, err := goods.GetGoodsByCategoryId(v.ID, 0, 0)
		if err != nil {
			res.SetRes(1, "error", err)
			ctx.JSON(http.StatusOK, res)
			return
		}
		formCategory.GoodsList = goodsList
		appInfo.CategoryList = append(appInfo.CategoryList, formCategory)
	}

	cart := models.Cart{}
	cartCount, err := cart.GetCartCountByUserId(int(userId))
	appInfo.CartCount = int(cartCount)
	if err != nil {
		res.SetRes(1, "error", err)
		ctx.JSON(http.StatusOK, res)
		return
	}
	res.SetRes(0, "success", appInfo)
	ctx.JSON(http.StatusOK, res)
}

// CheckLogin
//
//	@Description: /admin/index/checkLogin
//	@receiver *IndexHandler
//	@param ctx
func (*IndexHandler) CheckLogin(ctx *gin.Context) {
	_, exists := ctx.Get("id")
	res := utils.NewResponse()
	if exists {
		ctx.JSON(http.StatusOK, res)
	} else {
		res.SetRes(1, "失败", nil)
		ctx.JSON(http.StatusOK, res)
	}

}
